#include "Array.h"
#include <stdlib.h>
#include <string.h>

static void *ArrayMalloc(uint32_t _ulSize)
{
	return malloc(_ulSize);
}

uint8_t ArrayObjectCreate(ArrayObject_T *_tArray, uint32_t _ulSize)
{
	_tArray->ulMaxSize = _ulSize;
	_tArray->ulIndex = 0;
	_tArray->vpArray = ArrayMalloc(_ulSize);
	if(_tArray->vpArray == 0)
	{
		return Array_False;
	}
	memset(_tArray->vpArray, 0, _ulSize);
	return Array_True;
}

void ArrayObjectInit(ArrayObject_T *_tArray, uint8_t *_ucBuff, uint32_t _ulSize)
{
	_tArray->ulMaxSize = _ulSize;
	_tArray->ulIndex = 0;
	_tArray->vpArray = _ucBuff;
	memset(_tArray->vpArray, 0, _ulSize);
}

uint32_t ArrayOjectGetSize(ArrayObject_T *_tArray)
{
	return _tArray->ulIndex;
}

uint32_t ArrayOjectGetMaxSize(ArrayObject_T *_tArray)
{
	return _tArray->ulMaxSize;
}

void* ArrayOjectGetPtr(ArrayObject_T *_tArray)
{
	return _tArray->vpArray;
}

uint32_t ArrayObjectAdd(ArrayObject_T *_tArray, void *_vpBuff, uint32_t _ulSize)
{
	uint32_t ulWriteSize;
	
	if(_tArray->ulIndex + _ulSize <= _tArray->ulMaxSize)
	{
		ulWriteSize = _ulSize;
	}	
	else
	{
		ulWriteSize = 0;
	}
	
	memcpy(((uint8_t *)_tArray->vpArray + _tArray->ulIndex), _vpBuff, ulWriteSize);
	_tArray->ulIndex += ulWriteSize;
	
	return ulWriteSize;
}

// Return Write Size
uint32_t ArrayObjectAddForce(ArrayObject_T *_tArray, void *_vpBuff, uint32_t _ulSize)
{
	uint32_t ulWriteSize;
	
	if(_tArray->ulIndex + _ulSize <= _tArray->ulMaxSize)
	{
		ulWriteSize = _ulSize;
	}	
	else
	{
		ulWriteSize = _tArray->ulMaxSize - _tArray->ulIndex;
	}
	
	memcpy(((uint8_t *)_tArray->vpArray + _tArray->ulIndex), _vpBuff, ulWriteSize);
	_tArray->ulIndex += ulWriteSize;
	
	return ulWriteSize;

}

void ArrayObjectClear(ArrayObject_T *_tArray)
{
	memset(_tArray->vpArray, 0, _tArray->ulMaxSize);
	_tArray->ulIndex = 0;
	
}

uint32_t ArrayObjectOut(ArrayObject_T *_tArray, uint8_t *ucArray)
{
	uint32_t ulSize;
	
	ulSize = ArrayOjectGetSize(_tArray);
	memcpy(ucArray, _tArray->vpArray, _tArray->ulIndex);
	ArrayObjectClear(_tArray);
	
	return ulSize;
}




